<template>
  <section id="user-profile" class="section" v-show="visible" v-memo="[visible]">
    <div class="container">
      <div class="profile-container">
        <!-- 左侧用户基本信息 - 使用已创建的ProfileSidebar组件 -->
        <ProfileSidebar
          :avatar-url="userData.avatarUrl"
          :user-name="userData.userName"
          :user-role="userData.userRole"
          :stats="userData.stats"
        />
        
        <!-- 右侧详细信息和图表 -->
        <div class="profile-content">
          <!-- 基本资料 -->
          <div class="profile-section" v-memo="[userData.username, userData.email, userData.registrationDate, userData.memberLevel, userData.location, userData.specialization]">
            <h2>基本资料</h2>
            <div class="user-details">
              <div class="detail-item" v-for="detail in userDetails" :key="detail.key">
                <span class="detail-label">{{ detail.label }}</span>
                <span class="detail-value">{{ detail.value }}</span>
              </div>
            </div>
          </div>
          
          <!-- 使用数据图表 -->
          <div class="profile-section">
            <h2>使用数据分析</h2>
            <div class="chart-selector">
              <button 
                v-for="chart in chartTypes" 
                :key="chart.value"
                class="chart-btn"
                :class="{ active: currentChart === chart.value }"
                @click="switchChart(chart.value)"
              >{{ chart.label }}</button>
            </div>
            <div class="chart-container">
              <canvas ref="chartCanvas"></canvas>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import ProfileSidebar from './ProfileSidebar.vue'
import { ref, onMounted, watch, computed, nextTick, onBeforeUnmount } from 'vue'

export default {
  name: 'UserProfile',
  components: {
    ProfileSidebar
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userData: {
      type: Object,
      default: () => ({
        avatarUrl: 'https://picsum.photos/id/64/200/200',
        userName: '张三',
        userRole: 'AI产品开发者',
        username: 'zhangsan',
        email: 'zhangsan@example.com',
        registrationDate: '2023-06-15',
        memberLevel: '高级会员',
        location: '北京',
        specialization: '人工智能、机器学习',
        stats: {
          apiCalls: '1,245',
          activeDays: '45',
          projects: '12',
          points: '3,280'
        }
      })
    }
  },
  setup(props) {
    const currentChart = ref('api')
    const chartCanvas = ref(null)
    let chartInstance = null
    let chartUpdateTimeout = null
    
    // 图表类型配置，避免重复创建对象
    const chartTypes = [
      { label: 'API调用统计', value: 'api' },
      { label: '项目活跃度', value: 'project' },
      { label: '功能使用分布', value: 'usage' }
    ]
    
    // 图表数据缓存
    const chartDataCache = {
      api: {
        labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        data: [120, 190, 150, 220, 180, 100, 90],
        title: 'API调用统计'
      },
      project: {
        labels: ['项目A', '项目B', '项目C', '项目D', '项目E'],
        data: [65, 59, 80, 81, 56],
        title: '项目活跃度'
      },
      usage: {
        labels: ['语音AI', '图像AI', '文本AI', '推荐系统', '其他功能'],
        data: [30, 25, 20, 15, 10],
        title: '功能使用分布'
      }
    }
    
    // 计算用户详细信息，避免直接在模板中访问对象属性
    const userDetails = computed(() => {
      const safeData = props.userData || {}
      return [
        { key: 'username', label: '用户名', value: safeData.username || '-' },
        { key: 'email', label: '邮箱', value: safeData.email || '-' },
        { key: 'registrationDate', label: '注册时间', value: safeData.registrationDate || '-' },
        { key: 'memberLevel', label: '会员等级', value: safeData.memberLevel || '-' },
        { key: 'location', label: '所在地区', value: safeData.location || '-' },
        { key: 'specialization', label: '专业领域', value: safeData.specialization || '-' }
      ]
    })

    // 切换图表类型 - 防抖处理
    const switchChart = (chartType) => {
      currentChart.value = chartType
      
      // 清除之前的更新计时器
      if (chartUpdateTimeout) {
        clearTimeout(chartUpdateTimeout)
      }
      
      // 延迟更新图表，避免频繁切换时的性能问题
      chartUpdateTimeout = setTimeout(() => {
        updateChart()
      }, 50) // 短暂延迟，减少不必要的更新
    }

    // 更新图表数据
    const updateChart = () => {
      if (!chartInstance) return
      
      const chartData = chartDataCache[currentChart.value] || chartDataCache.api
      
      // 批量更新数据，减少更新次数
      chartInstance.data.labels = chartData.labels
      chartInstance.data.datasets[0].data = chartData.data
      chartInstance.data.datasets[0].label = chartData.title
      
      // 使用动画持续时间参数优化性能
      chartInstance.update('none') // 无动画更新，提高性能
    }

    // 初始化图表 - 使用ref而非getElementById
    const initChart = async () => {
      if (!props.visible) return
      
      await nextTick() // 确保DOM已更新
      
      if (!chartCanvas.value) return
      
      const Chart = window.Chart
      if (!Chart) {
        console.warn('Chart.js not loaded')
        // 尝试延迟重试
        setTimeout(initChart, 200)
        return
      }
      
      // 销毁现有图表实例
      if (chartInstance) {
        chartInstance.destroy()
        chartInstance = null
      }
      
      // 获取缓存的初始数据
      const initialData = chartDataCache[currentChart.value] || chartDataCache.api
      
      // 创建新图表实例
      chartInstance = new Chart(chartCanvas.value, {
        type: 'bar',
        data: {
          labels: initialData.labels,
          datasets: [{
            label: initialData.title,
            data: initialData.data,
            backgroundColor: 'rgba(79, 70, 229, 0.6)',
            borderColor: 'rgba(79, 70, 229, 1)',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          animation: {
            duration: 0 // 禁用动画以提高性能
          },
          scales: {
            y: {
              beginAtZero: true
            }
          },
          // 减少渲染开销
          elements: {
            bar: {
              borderSkipped: false
            }
          }
        }
      })
    }
    
    // 清理函数
    const cleanupChart = () => {
      if (chartUpdateTimeout) {
        clearTimeout(chartUpdateTimeout)
        chartUpdateTimeout = null
      }
      
      if (chartInstance) {
        chartInstance.destroy()
        chartInstance = null
      }
    }

    // 使用更高效的监听方式
    watch(() => props.visible, async (newValue) => {
      if (newValue) {
        await nextTick()
        // 使用requestAnimationFrame确保在浏览器渲染周期中初始化
        requestAnimationFrame(initChart)
      } else {
        // 隐藏时清理图表资源
        cleanupChart()
      }
    })
    
    // 监听currentChart变化，使用immediate选项避免重复调用
    watch(currentChart, () => {
      if (chartInstance) {
        updateChart()
      }
    })

    // 组件卸载时清理资源
    onBeforeUnmount(() => {
      cleanupChart()
    })

    return {
      currentChart,
      switchChart,
      chartCanvas,
      userDetails,
      chartTypes
    }
  }
}
</script>

<style scoped>
.section {
  padding: 80px 0;
  position: relative;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 0;
  background-color: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.profile-content {
  padding: 40px;
}

.profile-section {
  margin-bottom: 40px;
}

.profile-section h2 {
  font-size: 22px;
  color: var(--primary-color);
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--border-color);
}

.user-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 5px;
}

.detail-value {
  font-size: 16px;
  color: var(--text-color);
  font-weight: 500;
}

.chart-selector {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.chart-btn {
  padding: 8px 20px;
  background-color: var(--background-secondary);
  border: none;
  border-radius: 6px;
  color: var(--text-color);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.chart-btn:hover {
  background-color: var(--background-hover);
  color: var(--primary-color);
}

.chart-btn.active {
  background-color: var(--primary-color);
  color: white;
}

.chart-container {
  height: 300px;
  position: relative;
}

@media (max-width: 768px) {
  .section {
    padding: 60px 0;
  }
  
  .profile-container {
    grid-template-columns: 1fr;
  }
  
  .profile-content {
    padding: 30px 20px;
  }
  
  .user-details {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .chart-selector {
    flex-wrap: wrap;
  }
  
  .chart-btn {
    flex: 1;
    min-width: 120px;
  }
}
</style>